<template>
  <div class="teacher-score-management">
    <div class="header">
      <h2>成绩管理</h2>
      <div class="actions">
        <el-button type="primary" @click="showAddDialog">添加成绩</el-button>
        <el-button @click="exportScores">导出成绩</el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="学生姓名">
          <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchScores">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 成绩表格 -->
    <el-table 
      :data="scoreList" 
      style="width: 100%" 
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="studentName" label="学生姓名" width="120"></el-table-column>
      <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
      <el-table-column prop="score" label="成绩" width="80">
        <template #default="scope">
          <el-tag :type="getScoreType(scope.row.score)">
            {{ scope.row.score }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="examDate" label="考试日期" width="120"></el-table-column>
      <el-table-column prop="teacherName" label="任课教师" width="120"></el-table-column>
      <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="editScore(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteScore(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 添加/编辑成绩对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm">
      <el-form :model="scoreForm" :rules="rules" ref="scoreFormRef" label-width="80px">
        <el-form-item label="学生" prop="studentId">
          <el-select v-model="scoreForm.studentId" placeholder="请选择学生" style="width: 100%">
            <el-option 
              v-for="student in studentList" 
              :key="student.id"
              :label="`${student.name} (${student.studentId})`"
              :value="student.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input-number 
            v-model="scoreForm.score" 
            :min="0" 
            :max="100" 
            style="width: 100%"
            placeholder="请输入成绩">
          </el-input-number>
        </el-form-item>
        <el-form-item label="考试日期" prop="examDate">
          <el-date-picker
            v-model="scoreForm.examDate"
            type="date"
            placeholder="请选择考试日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="scoreForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import scoreAPI from '../api/score'

export default {
  name: 'TeacherScoreManagement',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('添加成绩')
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const scoreList = ref([])
    const studentList = ref([])
    const selectedScores = ref([])

    const searchForm = reactive({
      studentName: '',
      studentId: ''
    })

    const scoreForm = reactive({
      id: null,
      studentId: '',
      score: null,
      examDate: '',
      remark: ''
    })

    const rules = {
      studentId: [
        { required: true, message: '请选择学生', trigger: 'change' }
      ],
      score: [
        { required: true, message: '请输入成绩', trigger: 'blur' },
        { type: 'number', min: 0, max: 100, message: '成绩范围为0-100', trigger: 'blur' }
      ],
      examDate: [
        { required: true, message: '请选择考试日期', trigger: 'change' }
      ]
    }

    // 获取成绩类型样式
    const getScoreType = (score) => {
      if (score >= 90) return 'success'
      if (score >= 80) return ''
      if (score >= 60) return 'warning'
      return 'danger'
    }

    // 获取成绩列表
    const fetchScoreList = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          ...searchForm
        }
        const response = await scoreAPI.getPage(currentPage.value, pageSize.value)
        scoreList.value = response.data.records || []
        total.value = response.data.total || 0
      } catch (error) {
        ElMessage.error('获取成绩列表失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    // 搜索成绩
    const searchScores = () => {
      currentPage.value = 1
      fetchScoreList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      fetchScoreList()
    }

    // 显示添加对话框
    const showAddDialog = () => {
      dialogTitle.value = '添加成绩'
      dialogVisible.value = true
    }

    // 编辑成绩
    const editScore = (row) => {
      dialogTitle.value = '编辑成绩'
      Object.keys(scoreForm).forEach(key => {
        if (key in row) {
          scoreForm[key] = row[key]
        }
      })
      dialogVisible.value = true
    }

    // 删除成绩
    const deleteScore = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除学生 ${row.studentName} 的 ${row.subject} 成绩吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await scoreAPI.removeById(row.id)
        ElMessage.success('删除成功')
        fetchScoreList()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          console.error(error)
        }
      }
    }

    // 提交表单
    const submitForm = async () => {
      const scoreFormRef = ref()
      if (!scoreFormRef.value) return
      
      try {
        await scoreFormRef.value.validate()
        
        if (scoreForm.id) {
          await scoreAPI.update(scoreForm)
          ElMessage.success('修改成功')
        } else {
          await scoreAPI.save(scoreForm)
          ElMessage.success('添加成功')
        }
        
        dialogVisible.value = false
        fetchScoreList()
      } catch (error) {
        if (error !== false) { // 不是表单验证错误
          ElMessage.error(scoreForm.id ? '修改失败' : '添加失败')
          console.error(error)
        }
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.keys(scoreForm).forEach(key => {
        if (key === 'score') {
          scoreForm[key] = null
        } else {
          scoreForm[key] = ''
        }
      })
    }

    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedScores.value = selection
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchScoreList()
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchScoreList()
    }

    // 导出成绩
    const exportScores = () => {
      if (selectedScores.value.length === 0) {
        ElMessage.warning('请选择要导出的成绩')
        return
      }
      // TODO: 实现导出功能
      ElMessage.success('导出功能待实现')
    }

    onMounted(() => {
      fetchScoreList()
    })

    return {
      loading,
      dialogVisible,
      dialogTitle,
      currentPage,
      pageSize,
      total,
      scoreList,
      studentList,
      selectedScores,
      searchForm,
      scoreForm,
      rules,
      getScoreType,
      fetchScoreList,
      searchScores,
      resetSearch,
      showAddDialog,
      editScore,
      deleteScore,
      submitForm,
      resetForm,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      exportScores
    }
  }
}
</script>

<style scoped>
.teacher-score-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.actions {
  display: flex;
  gap: 10px;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}
</style>